/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rpt.bd.cenario;

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.Vector;

/**
 *
 * @author Roberto
 */
public class COrdenadorGradeBd implements Comparator {

    int colIndex;
    boolean ascending;

    COrdenadorGradeBd(int colIndex, boolean ascending) {
        this.colIndex = colIndex;
        this.ascending = ascending;
    }

    @Override
    public int compare(Object a, Object b) {
        Vector v1 = (Vector) a;
        Vector v2 = (Vector) b;
        Object o1 = v1.get(colIndex);
        Object o2 = v2.get(colIndex);

        // Treat empty strains like nulls
        if (o1 instanceof String && ((String) o1).length() == 0) {
            o1 = null;
        }
        if (o2 instanceof String && ((String) o2).length() == 0) {
            o2 = null;
        }

        // Sort nulls so they appear last, regardless
        // of sort order
        if (o1 == null && o2 == null) {
            return 0;
        } else if (o1 == null) {
            return 1;
        } else if (o2 == null) {
            return -1;
        } else if (o1 instanceof Comparable) {
            if (ascending) {
                return ((Comparable) o1).compareTo(o2);
            } else {
                return ((Comparable) o2).compareTo(o1);
            }
        } else {
            String s1 = o1.toString();
            String s2 = o2.toString();
            if (o1 instanceof CCampoRegistroBd) {
                CCampoRegistroBd c = (CCampoRegistroBd) o1;
                Object oo1 = c.getValorCampoBd();
                if (c.getEstruturaCampoRegistroBd().getTipoCampo() == ETipoCampoBd.data) {
                    if (oo1 instanceof String) {
                        s2 = new SimpleDateFormat("yyyy/MM/dd").format((String) oo1);
                    } else if (oo1 instanceof Date) {
                        s2 = new SimpleDateFormat("yyyy/MM/dd").format((Date) oo1);
                    }
                }
            }
            if (o2 instanceof CCampoRegistroBd) {
                CCampoRegistroBd c = (CCampoRegistroBd) o2;
                if (c.getEstruturaCampoRegistroBd().getTipoCampo() == ETipoCampoBd.data) {
                    Object oo2 = c.getValorCampoBd();
                    s2 = new SimpleDateFormat("yyyy/MM/dd").format((Date) oo2);
                }
            }
            if (ascending) {
                return s1.compareTo(s2);
            } else {
                return s2.compareTo(s1);
            }
        }
    }
}
